using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using DocumentCreationSystem.Models;
using MaterialDesignThemes.Wpf;
using Microsoft.Win32;

namespace DocumentCreationSystem.Views;

/// <summary>
/// 工具执行结果对话框
/// </summary>
public partial class ToolExecutionResultDialog : Window
{
    private readonly ProjectTool _tool;
    private readonly ToolExecutionResult _result;

    public ToolExecutionResultDialog(ProjectTool tool, ToolExecutionResult result)
    {
        InitializeComponent();
        
        _tool = tool;
        _result = result;
        
        InitializeDisplay();
    }

    private void InitializeDisplay()
    {
        // 设置标题
        TitleText.Text = $"{_tool.Name} - 执行结果";
        ExecutionTimeText.Text = $"执行时间: {_result.ExecutionTimeMs}ms";
        
        // 设置状态
        if (_result.IsSuccess)
        {
            StatusIcon.Kind = PackIconKind.CheckCircle;
            StatusIcon.Foreground = (System.Windows.Media.Brush)FindResource("MaterialDesignValidationSuccessBrush");
            ResultStatusIcon.Kind = PackIconKind.CheckCircle;
            ResultStatusIcon.Foreground = (System.Windows.Media.Brush)FindResource("MaterialDesignValidationSuccessBrush");
            StatusText.Text = "执行成功";
        }
        else
        {
            StatusIcon.Kind = PackIconKind.AlertCircle;
            StatusIcon.Foreground = (System.Windows.Media.Brush)FindResource("MaterialDesignValidationErrorBrush");
            ResultStatusIcon.Kind = PackIconKind.AlertCircle;
            ResultStatusIcon.Foreground = (System.Windows.Media.Brush)FindResource("MaterialDesignValidationErrorBrush");
            StatusText.Text = "执行失败";
        }
        
        // 设置消息
        MessageText.Text = _result.Message;
        
        // 设置错误信息
        if (!string.IsNullOrEmpty(_result.ErrorDetails))
        {
            ErrorCard.Visibility = Visibility.Visible;
            ErrorText.Text = _result.ErrorDetails;
        }
        
        // 设置结果数据
        if (_result.Data.Any())
        {
            var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
            ResultDataTextBox.Text = JsonSerializer.Serialize(_result.Data, jsonOptions);
        }
        else
        {
            ResultDataTextBox.Text = "无结果数据";
        }
        
        // 设置生成文件
        if (_result.GeneratedFiles.Any())
        {
            GeneratedFilesTab.Visibility = Visibility.Visible;
            foreach (var file in _result.GeneratedFiles)
            {
                var item = new ListBoxItem
                {
                    Content = CreateFileItem(file)
                };
                GeneratedFilesListBox.Items.Add(item);
            }
        }
        
        // 设置执行日志
        if (_result.Logs.Any())
        {
            LogsTab.Visibility = Visibility.Visible;
            LogsTextBox.Text = string.Join("\n", _result.Logs);
        }
    }

    private UIElement CreateFileItem(string filePath)
    {
        var grid = new Grid();
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        
        // 文件图标
        var icon = new PackIcon
        {
            Kind = GetFileIcon(filePath),
            VerticalAlignment = VerticalAlignment.Center,
            Margin = new Thickness(0, 0, 8, 0)
        };
        Grid.SetColumn(icon, 0);
        grid.Children.Add(icon);
        
        // 文件路径
        var pathText = new TextBlock
        {
            Text = filePath,
            VerticalAlignment = VerticalAlignment.Center,
            TextTrimming = TextTrimming.CharacterEllipsis
        };
        Grid.SetColumn(pathText, 1);
        grid.Children.Add(pathText);
        
        // 打开按钮
        var openButton = new Button
        {
            Content = "打开",
            Style = (Style)FindResource("MaterialDesignFlatButton"),
            Tag = filePath
        };
        openButton.Click += OpenFile_Click;
        Grid.SetColumn(openButton, 2);
        grid.Children.Add(openButton);
        
        return grid;
    }

    private PackIconKind GetFileIcon(string filePath)
    {
        var extension = Path.GetExtension(filePath).ToLower();
        return extension switch
        {
            ".txt" => PackIconKind.FileDocument,
            ".json" => PackIconKind.CodeJson,
            ".xml" => PackIconKind.FileDocument,
            ".zip" => PackIconKind.FolderZip,
            ".pdf" => PackIconKind.FileDocument,
            ".docx" => PackIconKind.FileWord,
            ".xlsx" => PackIconKind.FileExcel,
            _ => PackIconKind.File
        };
    }

    private void OpenFile_Click(object sender, RoutedEventArgs e)
    {
        if (sender is Button button && button.Tag is string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = filePath,
                        UseShellExecute = true
                    });
                }
                else
                {
                    MessageBox.Show($"文件不存在: {filePath}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开文件失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    private void CopyResult_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var resultText = $"工具: {_tool.Name}\n";
            resultText += $"状态: {(_result.IsSuccess ? "成功" : "失败")}\n";
            resultText += $"消息: {_result.Message}\n";
            resultText += $"执行时间: {_result.ExecutionTimeMs}ms\n";
            
            if (_result.Data.Any())
            {
                resultText += "\n结果数据:\n";
                var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
                resultText += JsonSerializer.Serialize(_result.Data, jsonOptions);
            }
            
            if (!string.IsNullOrEmpty(_result.ErrorDetails))
            {
                resultText += $"\n错误详情: {_result.ErrorDetails}";
            }
            
            Clipboard.SetText(resultText);
            MessageBox.Show("结果已复制到剪贴板", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"复制失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void SaveResult_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var saveDialog = new SaveFileDialog
            {
                Title = "保存执行结果",
                Filter = "JSON文件 (*.json)|*.json|文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                DefaultExt = "json",
                FileName = $"{_tool.Name}_Result_{DateTime.Now:yyyyMMdd_HHmmss}"
            };
            
            if (saveDialog.ShowDialog() == true)
            {
                var resultData = new
                {
                    Tool = new { _tool.Id, _tool.Name, _tool.Description },
                    Result = _result,
                    SavedAt = DateTime.Now
                };
                
                var json = JsonSerializer.Serialize(resultData, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(saveDialog.FileName, json);
                
                MessageBox.Show($"结果已保存到: {saveDialog.FileName}", "保存成功", 
                              MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void Close_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}
